package LeetCode.leetcode88;

/**
 * You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
 *
 * Merge nums1 and nums2 into a single array sorted in non-decreasing order.
 *
 * The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
 */
class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int p1 = 0;
        int p2 = 0;
        int curR = 0;
        int []res = new int[m+n];
        while (curR < m + n){
            if (p1 == m){
                while (p2 < n) {
                    res[curR++] = nums2[p2++];
                }
            }else if(p2 == n){
                while (p1 < m){
                    res[curR++] = nums1[p1++];
                }
            }else {
                if (nums1[p1] < nums2[p2]){
                    res[curR++] = nums1[p1++];
                }else {
                    res[curR++] = nums2[p2++];
                }
            }
        }
        p1 = 0;
        while (p1 < m + n){
            nums1[p1] = res[p1];
            p1++;
        }
    }
}